package com.cf.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cf.entity.ErpQuotationEntity;
import com.cf.mapper.ErpQtnProductCostEntityMapper;
import com.cf.mapper.ErpQuotationEntityMapper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;

@RestController
@RequestMapping("/erp/quotation")
public class ExportController extends AbstractController {
	@Resource
	ErpQuotationEntityMapper erpQuotationEntityMapper;
	@Resource
	ErpQtnProductCostEntityMapper erpQtnProductCostEntityMapper;

	private static final Logger log = LoggerFactory
			.getLogger(ExportController.class);

	@RequestMapping("/export")
	// @RequiresPermissions("erp:quotation:attach:file")
	public ResponseEntity<FileSystemResource> export(
			@RequestBody JSONObject prams) {

		String fileName = "";
		try {
			Integer quotationID = prams.getInteger("quotationID");

			QueryWrapper<ErpQuotationEntity> qw = new QueryWrapper<ErpQuotationEntity>();
			qw.eq("id", quotationID);
			ErpQuotationEntity qtn = erpQuotationEntityMapper.selectOne(qw);
			Map<String, Object> mapAll = BeanUtil.beanToMap(qtn);

			List<Map<String, Object>> lstMap = erpQtnProductCostEntityMapper
					.subTotal(quotationID);
			Map<String, Object> map = erpQtnProductCostEntityMapper
					.total(quotationID);
			mapAll.putAll(map);

			String serverPath = "";

			// serverPath =
			// ResourceUtils.getURL("classpath:static").getPath().replace("%20",
			// "
			// ").replace('/', '\\');
			serverPath = new File(ResourceUtils.getURL("classpath:").getPath())
					.getParentFile().getParentFile().getParent();

			// 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
			// 填充list 的时候还要注意 模板中{.} 多了个点 表示list
			// String templateFileName = serverPath +
			// "\\erp\\file\\template.xlsx";
			String templateFileName = "d:\\quotation\\template.xlsx";
			// 方案1 一下子全部放到内存里面 并填充
			// String fileName = TestFileUtil.getPath() + "listFill" +
			// System.currentTimeMillis() + ".xlsx";
			// 这里 会填充到第一个sheet， 然后文件流会自动关闭
			// EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(data());

			// 方案2 分多次 填充 会使用文件缓存（省内存）
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			fileName = "d:\\temp\\" + new DateTime().toString(sdf) + ".xlsx";
			ExcelWriter excelWriter = EasyExcel.write(fileName)
					.withTemplate(templateFileName).build();
			WriteSheet writeSheet = EasyExcel.writerSheet().build();

			FillConfig build = FillConfig.builder().forceNewRow(true).build();
			excelWriter.fill(mapAll, build, writeSheet);
			excelWriter.fill(lstMap, build, writeSheet);

			// 千万别忘记关闭流
			excelWriter.finish();

			File file = new File(fileName);
			if (file.exists()) {
				HttpHeaders headers = new HttpHeaders();
				headers.add("Cache-Control",
						"no-cache, no-store, must-revalidate");
				headers.add("Content-Disposition",
						"attachment; filename=" + file.getName());
				headers.add("Pragma", "no-cache");
				headers.add("Expires", "0");
				headers.add("Last-Modified", new Date().toString());
				headers.add("ETag", String.valueOf(System.currentTimeMillis()));
				BodyBuilder bb = ResponseEntity.ok().headers(headers)
						.contentLength(file.length()).contentType(MediaType
								.parseMediaType("application/octet-stream"));
				ResponseEntity<FileSystemResource> rf = bb
						.body(new FileSystemResource(file));
				return rf;
			} else
				return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}
